package com.mingtu.guards.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.room.ReportedEvent;
import com.mingtu.common.room.ReportedEventDao;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.view.ContainsEmojiEditText;
import com.mingtu.home.adapter.LabelAdapter;
import com.mingtu.home.bean.TagBean;
import com.mingtu.guards.R;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.utils.MySPTools;
import com.mingtu.uploadevent.view.ReportPictureVideo2;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.MAX_ZOOM;
import static com.mingtu.guards.utils.MyConstant.UPLOAD_MAP_RESULTCODE;

public class ReportedEventActivity extends MyBaseActivity {
    @BindView(R.id.edit_describe)
    EditText editDescribe;
    @BindView(R.id.tvAddress)
    TextView tvAddress;
    @BindView(R.id.tv_total_text_count)
    TextView tvTotalTextCount;
    @BindView(R.id.but_submit)
    Button butSubmit;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.layout_type)
    LinearLayout layoutType;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.iv_location_event)
    ImageView ivLocationEvent;
    @BindView(R.id.edit_address)
    ContainsEmojiEditText editAddress;
    @BindView(R.id.report_picture_video)
    ReportPictureVideo2 reportPictureVideo;
    private List<TagBean.TagsBean> DataBean = new ArrayList<>();
    private LabelAdapter labelAdapter;
    private String address;
    private String lat;
    private String lng;
    private String tagValue = "";
    private String editContent;
    private List<Marker> markers = new ArrayList<>();
    private ArrayList<HashMap<String, Object>> mylist = new ArrayList<>();
    private int totalTextCount = 200;
    private AMap aMap;
    private MapView mapView;
    private int textNum = 0;
    private ArrayList<String> typeList = new ArrayList<>();
    private OptionsPickerView pvOptions;
    private List<LocalMedia> localMediaList;
    private List<HashMap<String, String>> hashMapList = new ArrayList<>(); //存储要上报的图片、视频的信息
    private List<HashMap<String, Object>> offlineInfoList = new ArrayList<>(); //存储未上报的信息
    private HashMap<String, Object> offlineInfoHashMap = new HashMap<>(); //存储未上报的信息
    private boolean netWorkState = true;
    private ReportedEventDao reportedEventDao;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reported;
    }

    @Override
    protected void initView() {
        setModuleTitle("上报事件");
        setTitleBarBackground(getResources().getDrawable(com.mingtu.home.R.drawable.line_bottom));

//        labelAdapter = new LabelAdapter(context, DataBean);
//        mgvLable.setAdapter(labelAdapter);
//        labelAdapter.setOnItemClickListener(labelOnItemClickListener);


        editDescribe.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                textNum -= count;
                tvTotalTextCount.setText(textNum + "");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textNum += count;
                tvTotalTextCount.setText(textNum + "");
            }

            @Override
            public void afterTextChanged(Editable s) {
                MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                String str = MyUtills.getEditText(editDescribe);
                editDescribe.setSelection(str.length());
            }
        });

        int screenWidth = ScreenUtils.getScreenWidth();
        int itemWidth = (screenWidth - SizeUtils.dp2px(5) * 2 - SizeUtils.dp2px(15) * 4) / 3;
        reportPictureVideo.setItemWidth(itemWidth);

    }


    @Override
    protected void initData() {
        address = SPStaticUtils.getString(SPTools.address);
        lat = SPStaticUtils.getString(SPTools.lat);
        lng = SPStaticUtils.getString(SPTools.lng);
//        tvTotalTextCount.setText(totalTextCount + "");

        if (!StringUtils.isEmpty(address)) {
            tvAddress.setText(address);
            editAddress.setText(address);
        } else {
            //只有GPS定位的时候，addredd为空，这个时候需要逆地址解析出地址
            if (!StringUtils.isEmpty(lng) && !StringUtils.isEmpty(lat)) {
                ServiceSettings.updatePrivacyShow(context, true, true);
                ServiceSettings.updatePrivacyAgree(context, true);
                try {
                    GeocodeSearch geocoderSearch = new GeocodeSearch(context);
                    geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                        @Override
                        public void onGeocodeSearched(GeocodeResult result, int rCode) {

                        }

                        @Override
                        public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                            MyLogUtil.e("formatAddress", "rCode:" + rCode);
                            if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                                if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {
                                    String formatAddress = result.getRegeocodeAddress().getFormatAddress();
                                    MyLogUtil.e("formatAddress", "formatAddress:" + formatAddress);
                                    address = formatAddress;
                                    tvAddress.setText(formatAddress);
                                    editAddress.setText(address);
                                }
                            }
                        }
                    });
                    LatLonPoint lp = new LatLonPoint(Double.parseDouble(lat), Double.parseDouble(lng));
                    RegeocodeQuery query = new RegeocodeQuery(lp, 200, GeocodeSearch.AMAP);
                    geocoderSearch.getFromLocationAsyn(query);
                } catch (AMapException e) {
                    e.printStackTrace();
                }

            }
        }


        reportedEventDao = BaseApplication.getBaseApplication().getReportedEventDao();

    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_map1:
                        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                        break;
                    case R.id.rb_map2:
                        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
                        break;
                }
            }
        });

        String longitude = SPStaticUtils.getString(SPTools.lng);
        String latitude = SPStaticUtils.getString(SPTools.lat);
        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
            LatLng location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
            //添加Marker
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(location)
                    .icon(BitmapDescriptorFactory.fromResource(com.mingtu.home.R.mipmap.sb_icon_wz));
            Marker marker = aMap.addMarker(markerOptions);
            markers.add(marker);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }
    }

    @Override
    protected void getData() {
        getEventTags();
    }

    @Override
    public void onNetChange(boolean netWorkState) {
        super.onNetChange(netWorkState);
        this.netWorkState = netWorkState;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            //销毁地图对象
            if (aMap != null) {
                mapView.onDestroy();
            }

            for (Marker marker : markers) {
                marker.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == UPLOAD_MAP_RESULTCODE) {
            lat = SPStaticUtils.getString(MySPTools.UPLOAD_LAT);
            lng = SPStaticUtils.getString(MySPTools.UPLOAF_LNG);
            String addressUpload = SPStaticUtils.getString(MySPTools.UPLOAF_ADDRESS);
            editAddress.setText(addressUpload);
            editAddress.setSelection(addressUpload.length());
        }
    }

    @OnClick({R.id.but_submit, R.id.layout_type, R.id.iv_location_event})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.but_submit:
                KeyboardUtils.hideSoftInput(ReportedEventActivity.this);
                //提交操作
                editContent = MyUtills.getEditText(editDescribe);


                if (StringUtils.isEmpty(tagValue)) {
                    ToastUtils.showLong("请选择标签");
                    return;
                }


                if (StringUtils.isEmpty(lat) || StringUtils.isEmpty(lng)) {
                    ToastUtils.showLong("地址获取失败！");
                    return;
                }

                if (StringUtils.isEmpty(editContent)) {
                    ToastUtils.showLong("请填写上报内容！");
                    return;
                }


                hashMapList = reportPictureVideo.getHashMapList();
                List<LinkedHashMap<String, Object>> picVideoUrl = reportPictureVideo.getPicVideoUrl();

                if (hashMapList.size() == 0) {
                    ToastUtils.showLong("请上传视频、图片相关文件！");
                    return;
                }


                localMediaList = reportPictureVideo.getLocalMedisList();

                for (int i = 0; i < picVideoUrl.size(); i++) {
                    LinkedHashMap<String, Object> hashMap = picVideoUrl.get(i);
                    mylist.add(hashMap);
                }

                uploadEvent();
                break;

            case R.id.layout_type:
                if (typeList.size() == 0) {
                    ToastUtils.showLong("未获取到标签数据！");
                    return;
                }
                pvOptions.show();
                break;
            case R.id.iv_location_event:
                IntentUtils.getInstance().readyGoForResult(ReportedEventActivity.this, ReportMapActivity.class, UPLOAD_MAP_RESULTCODE);
                break;
        }
    }

    /**
     * 上报事件
     */
    private void uploadEvent() {
        butSubmit.setEnabled(false);
        String myAddress = UIUtils.getEditText(editAddress);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("address", StringUtils.isEmpty(myAddress) ? address : myAddress);
        hashMap.put("lat", lat);
        hashMap.put("lng", lng);
        hashMap.put("eventDesc", editContent);
        hashMap.put("tag", tagValue);
        hashMap.put("attachVOS", mylist);
        String str = GsonUtils.toJson(hashMap);

        //未联网或者mylist中的数据个数和localMediaList中的数据个数不一致的时候（此时说明有部分文件因为网络原因没有生成链接）
        if (!netWorkState || mylist.size() != localMediaList.size()) {
            //没有网络的时候将提交内容存起来,并添加创建时间,提交前判断是否有待上报的信息
            saveReportedEventData(str);
            return;
        }

        OkGo.<String>post(MyConstant.POST_UPLOAD)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        int responseCode = response.code();
                        if (responseCode == 400) {
                            saveReportedEventData(str);
                            return;
                        }
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String success = jsonObject.getString("success");
                            if (success.indexOf("ok") != -1) {
                                ToastUtils.showLong("上报成功！");
                                butSubmit.setEnabled(true);
                                //实例化Timer类 ,守护线程，不在后台一直运行
                                EventBus.getDefault().post(new MyEventBus(MyConstant.REFRESH_REPORTED_DATA));
                                ActivityUtil.removeActivity(ReportedEventActivity.this);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                        butSubmit.setEnabled(true);
                        saveReportedEventData(str);
                    }
                });
    }

    /**
     * 条件选择器
     */

    private void initOptionPicker() {//条件选择器初始化

        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {

                String type = typeList.get(options1);
                tagValue = type;
                tvType.setText(type);
                tvType.setTextColor(getResources().getColor(R.color.text_color333));
            }
        })

                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(getResources().getColor(R.color.black_eee))
                .setCancelColor(getResources().getColor(R.color.text_cancel_color))
                .setSubmitColor(getResources().getColor(R.color.text_submit_color))
                .setTextColorCenter(getResources().getColor(R.color.colorPrimary))
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .setOutSideColor(getResources().getColor(R.color.translucence)) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {

                    }
                })
                .build();

        pvOptions.setSelectOptions(0);
        pvOptions.setPicker(typeList);//进入页面就获取，默认不显示

    }

    /**
     * 事件标签
     */
    private void getEventTags() {
        OkGo.<String>post(MyConstant.POST_SELECT_TAG)
                .tag(this)
                .upJson("")
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        getTagsCommon(response);
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        getTagsCommon(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    private void getTagsCommon(Response<String> response) {
        String result = response.body();
        if (!StringUtils.isEmpty(result)) {
            Gson gson = GsonFactory.getSingletonGson();
            TagBean tagBean = new TagBean();
            tagBean = gson.fromJson(result, TagBean.class);
            List<TagBean.TagsBean> dataBeans = tagBean.getTags();

            if (dataBeans != null) {
                if (dataBeans.size() > 0) {
                    for (int i = 0; i < dataBeans.size(); i++) {
                        TagBean.TagsBean tagsBean = dataBeans.get(i);
                        String tag = tagsBean.getValue();
                        typeList.add(tag + "");
                    }
                    initOptionPicker();
                }
            }

//                            DataBean.addAll(dataBeans);
//                            labelAdapter.upData(DataBean);
        }
    }

    /**
     * 显示提示信息
     */
    private void showPopup(final String str, ReportedEvent reportedEvent) {
        butSubmit.setEnabled(true);
        BasePopupView popupView = new XPopup.Builder(this)
                .isDestroyOnDismiss(false)
                .dismissOnTouchOutside(false)
                .hasShadowBg(true)
                .asConfirm(context.getResources().getString(R.string.text_tip), "网络不好，上报内容是否保存到本地？",
                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        reportedEventDao.insertEvent(reportedEvent);
                                        ActivityUtil.removeActivity(ReportedEventActivity.this);
                                    }
                                }).start();

                            }
                        }, null, false);
        popupView.show();

    }

    /**
     * 保存上报事件数据
     */
    private void saveReportedEventData(String str) {
        long timeStamp = System.currentTimeMillis();
        ReportedEvent reportedEvent = new ReportedEvent();
        reportedEvent.setAddress(address);
        reportedEvent.setLat(lat);
        reportedEvent.setLng(lng);
        reportedEvent.setTag(tagValue);
        reportedEvent.setMemo(editContent);
        reportedEvent.setCreateTime(timeStamp + "");

        List<ReportedEvent.AttachVOSBean> attachVOS = new ArrayList<>();
        for (int i = 0; i < mylist.size(); i++) {
            HashMap<String, Object> myHashMap = mylist.get(i);
            String type = (String) myHashMap.get("type");
            String url = (String) myHashMap.get("url");
            ReportedEvent.AttachVOSBean attachVOSBean = new ReportedEvent.AttachVOSBean();
            attachVOSBean.setType(type);
            attachVOSBean.setUrl(url);
            attachVOS.add(attachVOSBean);
        }
        reportedEvent.setAttachVOS(attachVOS);

        List<ReportedEvent.MyattachVOSBean> myattachVOSBeans = new ArrayList<>();
        for (int i = 0; i < hashMapList.size(); i++) {
            HashMap<String, String> myHashMap = hashMapList.get(i);
            String pathName = (String) myHashMap.get("pathName");
            String type = (String) myHashMap.get("type");
            ReportedEvent.MyattachVOSBean myattachVOSBean = new ReportedEvent.MyattachVOSBean();
            myattachVOSBean.setPathName(pathName);
            myattachVOSBean.setType(type);
            myattachVOSBeans.add(myattachVOSBean);
        }
        reportedEvent.setMyattachVOS(myattachVOSBeans);

        showPopup(str, reportedEvent);
    }
}